//
//  YDTuiGuangViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2017/11/21.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDTuiGuangViewController.h"
#import "YDTuiGuangTableHeaderView.h"
#import "YDMyMemberCell.h"
#import "YDInvitelinkCell.h"
#import "YDTuiGuangCellHeadView.h"
#import "YDTuiGuangMemberModel.h"

@interface YDTuiGuangViewController ()<UITableViewDelegate, UITableViewDataSource,SYTuiGuangCellHeadViewDelegate , SYInvitelinkCellDelegate>

@property (nonatomic, weak) UITableView *tableView;

//当前邀请人的基本信息
@property (nonatomic , strong) NSDictionary *dict;
//当前页码
@property (nonatomic , assign) NSInteger currentPage;

@property (nonatomic, strong) NSMutableArray *modelArray;

@property (nonatomic , weak)  YDTuiGuangTableHeaderView *tableHeaderView;

@property (nonatomic, assign) SYTuiGunagStyle dataStyle;
//引导登录页面
@property (nonatomic, strong) SYGuideLoginView *guideLoginView;

//我的用户没有数据
@property (nonatomic, strong) SYNoDataView *noDataView;



@end

@implementation YDTuiGuangViewController

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    
    [self setupNav];
  
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //从banner跳进来 未登录问题
    if ([SYUserInformation sharedInstance].isLogin)
    {
        [self promotionInformation];
    }else
    {
        [self guideLoginView];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)removeNoDataView
{
    if (_noDataView) {
        [_noDataView removeFromSuperview];
        _noDataView = nil;
    }
}
- (void)setupNav
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.title = @"推广";
}
-(void)setUpDataManger
{
    
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadPromotionInformationFirstList)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES ;
    //隐藏状态
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
    
    MJGIFFooter *footer = [MJGIFFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
    
}
//加载推广人基本信息
-(void)promotionInformation
{
    if (_tableView) {
        self.tableView.mj_footer.hidden = YES;
    }
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:PromotionInformation WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.dict = resultDict[@"result"];
            [self tableView];
            [self tableHeaderView];
            self.tableHeaderView.dict = self.dict;
            [self setUpDataManger];
            [self.tableView reloadData];
        }else{
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
    }];
}

-(void)loadData
{
    if (self.dataStyle == 0) {//加载推广人基本信息
        [self promotionInformation];
    }else{//加载已推广信息
        [self loadPromotionInformationFirstList];
    }
}
-(void)loadPromotionInformationFirstList
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(10) forKey:@"size"];
    [dict setObject:@(0) forKey:@"page"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:PromotionLists WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentPage = [resultDict[@"result"][@"number"] integerValue];
            self.modelArray = [YDTuiGuangMemberModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            if (self.modelArray.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            [self.tableView reloadData];
            
            YDMyMemberCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            
            if (!self.modelArray.count) {
                //没有推广用户 显示空荡荡 第一个cell影藏
                [self noDataView];
                cell.hidden = YES;
                self.tableView.mj_footer.hidden = YES;
            }else
            {
                cell.hidden = NO;
                self.tableView.mj_footer.hidden = NO;
                [self removeNoDataView];
            }
            
          
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = YES;
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
    }] ;
}
-(void)loadMoreData
{
//    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(10) forKey:@"size"];
    [dict setObject:@(self.currentPage + 1) forKey:@"page"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:PromotionLists WithSuccessBlock:^(NSDictionary *resultDict) {
//        [[PZProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_footer endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentPage = [resultDict[@"result"][@"number"] integerValue];
            NSArray *array = [YDTuiGuangMemberModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            [self.modelArray addObjectsFromArray:array];
            
            if (array.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            [self.tableView reloadData];
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
//        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = NO;
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"加载出错~" isExistNav:YES];
    }] ;
}

#pragma tableHeaderView
-(YDTuiGuangTableHeaderView *)tableHeaderView
{
    if (_tableHeaderView == nil) {
        YDTuiGuangTableHeaderView *tableHeaderView = [YDTuiGuangTableHeaderView tuiGuangTableHeaderViewWithDataDict:self.dict];
        CGFloat tableHeaderViewH = isPhoneX ? rateX812(90) : rate750(90);
        tableHeaderView.frame = CGRectMake(0, 0, LKScreenW, tableHeaderViewH);
        self.tableView.tableHeaderView = tableHeaderView;
        _tableHeaderView = tableHeaderView;
    }
    return _tableHeaderView;
}
#pragma  mark - getter
-(UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect tableViewFrame;
        if (isPhoneX) {
            tableViewFrame = CGRectMake(0, 0, LKScreenW, LKScreenH - 88);
        }else{
            tableViewFrame = CGRectMake(0, 0, LKScreenW, LKScreenH - 64);
        }
        UITableView *tableView =  [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.bounces = NO;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.separatorInset = UIEdgeInsetsMake(0, rate375(20), 0, rate375(20));
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
        
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate && UITableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataStyle ? self.modelArray.count+1 : 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(32) : rate750(32);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataStyle == SYTuiGunagLink) {
        CGFloat topViewH = isPhoneX ? rateX812(90) : rate750(90);
        CGFloat sectionH = isPhoneX ? rateX812(32) : rate750(32);
        return LKScreenH - self.navigationController.navigationBar.height - topViewH - sectionH;
    }else{
        return 50;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.dataStyle == SYTuiGunagLink ) {
        YDInvitelinkCell *cell = [YDInvitelinkCell cellWithTableview:tableView];
        cell.dict = self.dict;
        cell.delegate = self;
        return cell;
    }else{
        YDMyMemberCell *cell = [YDMyMemberCell cellWithTableview:tableView];
        
        if (indexPath.row == 0) {
            YDTuiGuangMemberModel *model = [YDTuiGuangMemberModel new];
            model.index = indexPath.row;
            model.phoneNumber = @"用户名";
            model.money = @"注册时间";
            cell.model = model;
        }else{
            YDTuiGuangMemberModel *model = self.modelArray[indexPath.row - 1];
            model.index = indexPath.row;
            cell.model = model;
            
        }
        
        return cell;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    
    YDTuiGuangCellHeadView *headerView = [YDTuiGuangCellHeadView headerViewWithTableView:tableView];
    headerView.delegate = self;
    return headerView;
}

#pragma PZInvitelinkCellDelegate
-(void)invitelinkCellDidPastedInvitelinkCode:(NSString *)invitelinkCode
{
    [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"复制成功" isExistNav:NO];
}

/***********PZHomeTableViewHeaderViewDelegate***************/
-(void)homeTableViewHeaderView:(YDTuiGuangCellHeadView *)headerView didClickButtonTag:(NSInteger)buttonTag
{
    if (buttonTag == 0) {
        self.dataStyle = SYTuiGunagLink;
        [self removeNoDataView];
        [self.tableView reloadData];
        self.tableView.bounces = NO;
        [self loadData];
    }else{
        self.dataStyle = SYTuiGunagMember;
        [self.tableView reloadData];
        self.tableView.bounces = YES;
         [self loadData];
    }
}


-(SYGuideLoginView *)guideLoginView
{
    if (!_guideLoginView) {
        if (![SYUserInformation sharedInstance].isLogin) {
            //没有登录贴引导登录展位图
            
            _guideLoginView = [[SYGuideLoginView alloc] init];
            [self.view addSubview:_guideLoginView];
            [_guideLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self.view);
                make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
            }];
            __weak typeof(self)weself = self;
            [_guideLoginView setClickBlock:^(BOOL isClick) {
                YDLoginController *loginVC = [[YDLoginController alloc] init];
                loginVC.loginStyle = Login_Present;
                YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
                [weself presentViewController:baseNav animated:YES completion:nil];
            }];
        }
    }
    return _guideLoginView;
}


-(SYNoDataView *)noDataView
{
    if (_noDataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(196) : rate750(196);
        CGFloat dataY = isPhoneX ? rateX812(190) : rate750(190);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        //wuneirong   wuxinhao
        SYNoDataView *noDataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"" IsCanSeeBuyButton:NO];
        [self.tableView addSubview:noDataView];
        _noDataView = noDataView;
    }
    return _noDataView;
}


@end
